package com.ming.config;

import com.ming.config.properties.FileUploadProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 文件上传配置类
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class FileUploadConfig implements WebMvcConfigurer {

    private final FileUploadProperties fileUploadProperties;

    /**
     * 配置静态资源映射，用于文件访问（仅本地存储时生效）
     */
    @Override
    @ConditionalOnProperty(name = "file.type", havingValue = "local", matchIfMissing = true)
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath = fileUploadProperties.getLocal().getUploadPath();

        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
            log.info("创建文件上传目录: {}", uploadPath);
        }

        // 配置文件访问路径映射
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:" + uploadPath + "/");

        log.info("配置本地文件资源映射: /files/** -> file:{}", uploadPath);
    }
}